package com.runen.wnhz.runen.ui.fragment.minem;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.google.gson.Gson;
import com.runen.wnhz.runen.R;
import com.runen.wnhz.runen.bean.MyOrderBean;
import com.runen.wnhz.runen.common.utils.ACacheUtlis;
import com.runen.wnhz.runen.common.utils.NetStateUtils;
import com.runen.wnhz.runen.common.utils.NetUtils;
import com.runen.wnhz.runen.common.utils.OkHttpUtils;
import com.runen.wnhz.runen.common.utils.ToastUtil;
import com.runen.wnhz.runen.data.entity.UserBean;
import com.runen.wnhz.runen.ui.activity.login.LoginForPersonalActivity;
import com.runen.wnhz.runen.ui.adapter.puadapter.MyOrderListAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class AllOrderFragment extends Fragment {

    @BindView(R.id.list_allOrder)
    ListView listAllOrder;
    Unbinder unbinder;
    @BindView(R.id.smartRefresh)
    SmartRefreshLayout smartRefresh;
    private int currentPage = 0;
    private int totalPage = 0;
    private int orderType = 10;
    private String token;
    private boolean hasNextPage = false;
    private boolean isRefresh = false;
    private boolean isLoadMore = false;
    private List<MyOrderBean.DataBean.ListBean> listBeans;
    private MyOrderListAdapter adapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = View.inflate(getActivity(), R.layout.all_order_fragment_layout, null);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
        setListener();
        if(-1 == orderType){
            setUserVisibleHint(true);
        }
    }

    private void initData() {
        ACacheUtlis aCacheUtlis = ACacheUtlis.getInstance();
        if (aCacheUtlis != null) {
            UserBean reqeustUser = aCacheUtlis.getReqeustUser(getActivity());
            if (reqeustUser != null) {
                token = reqeustUser.getToken();
            }
        }
        listBeans = new ArrayList<>();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            Bundle bundle = getArguments();
            orderType = bundle.getInt("orderType", -1);
            getAllOrderDataFromServer(String.valueOf(currentPage));
        }
    }

    private void setListener(){
        smartRefresh.setEnableAutoLoadMore(false);
        smartRefresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if(NetStateUtils.isNetworkAvalible(getActivity())){
                    if(hasNextPage){
                        isLoadMore = true;
                        int tempCurrentPage = currentPage + 1;
                        getAllOrderDataFromServer(String.valueOf(tempCurrentPage));
                    }else{
                        ToastUtil.showToast("暂无更多数据");
                        smartRefresh.finishLoadMore(true);
                    }
                }else{
                    ToastUtil.showToast("当前暂无网络");
                    smartRefresh.finishLoadMore(false);
                }

            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if(NetStateUtils.isNetworkAvalible(getActivity())){
                    isRefresh = true;
                    int tempCurrentPage = 0;
                    getAllOrderDataFromServer(String.valueOf(tempCurrentPage));
                }else{
                    ToastUtil.showToast("当前暂无网络");
                   smartRefresh.finishRefresh(false);
                }
            }
        });
    }

    private void getAllOrderDataFromServer(String pageNum) {
        if (token != null) {
            FormBody formBody = new FormBody.Builder().add("token", token).add("page", pageNum).add("type", String.valueOf(orderType)).build();
            Request request = new Request.Builder().url(NetUtils.MY_ORDER_INFO).post(formBody).build();
            Call newCall = OkHttpUtils.getOkHttpClient().newCall(request);
            newCall.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast("数据请求失败");
                            finishRefreshOrLoadMoreAnimation(false);
                        }
                    });
                }

                @Override
                public void onResponse(Call call, final Response response) throws IOException {
                    try {
                        handleOrderData(response);
                    } catch (IOException e) {
                        e.printStackTrace();
                        ToastUtil.showToast("数据请求出现异常");
                        finishRefreshOrLoadMoreAnimation(false);
                    }
                }
            });
        }
    }

    private void finishRefreshOrLoadMoreAnimation(boolean isSuccessful){
        if(isLoadMore){
            smartRefresh.finishLoadMore(isSuccessful);
            isLoadMore = false;
        }
        if(isRefresh){
            smartRefresh.finishRefresh(isSuccessful);
            isRefresh = false;
        }
    }

    private void handleOrderData(Response response) throws IOException {
        if (response.isSuccessful()) {
            ResponseBody responseBody = response.body();
            final String json = responseBody.string();
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    parseJson(json);
                }
            });

        }
    }

    private void parseJson(String json) {
        MyOrderBean myOrderBean = new Gson().fromJson(json, MyOrderBean.class);
        if ("1".equals(myOrderBean.getRe())) {
            MyOrderBean.DataBean dataBean = myOrderBean.getData();
            if (dataBean != null) {
                hasNextPage = "1".equals(dataBean.getIs_page());
                totalPage = Integer.parseInt(dataBean.getSum_page());
                currentPage = Integer.parseInt(dataBean.getPage());
                if(isRefresh){
                    List<MyOrderBean.DataBean.ListBean> listBeansOther = dataBean.getList();
                    if(listBeans.size() != 0){
                        listBeans.clear();
                    }
                    if(listBeansOther.size() != 0){
                       currentPage = 0;
                    }
                    listBeans.addAll(listBeansOther);
                    if(adapter == null){
                        adapter = new MyOrderListAdapter(getActivity(),listBeans);
                        listAllOrder.setAdapter(adapter);
                    }else{
                        adapter.notifyDataSetChanged();
                    }
                    isRefresh = false;
                    smartRefresh.finishRefresh(true);
                    return;
                }
                if(isLoadMore){
                    List<MyOrderBean.DataBean.ListBean> listBeansOther = dataBean.getList();
                    if(listBeansOther.size() != 0){
                        currentPage = currentPage + 1;
                    }
                    listBeans.addAll(listBeansOther);
                    if(adapter == null){
                        adapter = new MyOrderListAdapter(getActivity(),listBeans);
                        listAllOrder.setAdapter(adapter);
                    }else{
                        adapter.notifyDataSetChanged();
                    }
                    isLoadMore = false;
                    smartRefresh.finishLoadMore(true);
                    return;
                }
                if(listBeans.size() != 0){
                    listBeans.clear();
                }
                listBeans.addAll(dataBean.getList());
                adapter = new MyOrderListAdapter(getActivity(),listBeans);
                listAllOrder.setAdapter(adapter);
            }
        } else if ("0".equals(myOrderBean.getRe())) {
            ToastUtil.showToast(myOrderBean.getInfo());
            finishRefreshOrLoadMoreAnimation(false);
        }else if("-1".equals(myOrderBean.getRe())){
            finishRefreshOrLoadMoreAnimation(false);
            startActivity(new Intent(getActivity(), LoginForPersonalActivity.class));
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
